/// <reference path="../../../../../global.d.ts" />

/* global $ backVar layer */

// 回填各个小标签
function writeBackXiaoleiTag () {
  layer.msg('加载中', {
    icon: 16,
    shade: 0.01
  })
  if (backVar.dalei !== '') {
    $('#dalei').val(backVar.dalei)
    $(`#dalei`).change()
  }
  for (let e of backVar.tag.check) {
    // 这是非常脏的hack方式……因为执行这个语句的时候tageditor没有建立，所以就延迟0.5喵来执行这个事情
    console.dir(backVar.tag.check)
    setTimeout(function _this () {
      let value = $(`input[name='check[]'][value='${e}']`)
      if (value.length === 0) {
        console.log('try again')
        setTimeout(_this, 100)
      } else {
        /* 得到小类的显示值，用于直接push */
        let _value = value.attr('id')
        console.log(`done: ${_value}`)
        $(`#xiaolei_tag_list`).tagEditor('addTag', _value, true)
      }
    }, 0)
  }
}
function writeBackTag () {
  // i 就是tag中的每一项，实际意义代表每一个tag类别
  for (let i of Object.keys(backVar.tag)) {
    console.log(i)
    if (i !== 'check') {
      for (let e of backVar.tag[i]) {
        // 获取前缀，例子：check_shouru -> shouru
        let qianzui = i.replace(/check_/, '')
        // 这是非常脏的hack方式……因为执行这个语句的时候tageditor没有建立，所以就延迟0.5喵来执行这个事情
        setTimeout(function () { $(`#${qianzui}_tag_list`).tagEditor('addTag', e, true) }, 500)
      }
    } else if (i === 'check') {
      writeBackXiaoleiTag()
    }
  }
}
// 回填各个要求
function writeBackxiangxi () {
  for (let i of Object.keys(backVar.yaoqiu)) {
    // console.log(backVar.yaoqiu[i])
    if (i === 'fangkuan_fangshi_se' || i === 'zhengxin_xianshi') {
      $(`#${i}`).val(backVar.yaoqiu[i])
    } else if (i === 'shangmen') {
      for (let j of backVar.yaoqiu[i]) {
        $(`input[name='shangmen[]'][value='${j}']`).click()
      }
    } else if (i === 'jinzhi') {
      $('.hangye_ban.sec_box input').each((index, item) => {
        $(item).prop('checked', false)
      })
      // 公交司机,美容,美发,快递公司
      let rawValue = `${backVar.yaoqiu[i]}`.split(',')
      if (rawValue.length === 0) continue
      for (let value of rawValue) {
        $(`.hangye_ban input[value='${value}']`).prop('checked', true).change()
      }
    } else if (
      i === 'danwei' ||
      i === 'peiou' ||
      i === 'zhixi' ||
      i === 'qingsu' ||
      i === 'tongshi' ||
      i === 'pengyou') {
      if (backVar.yaoqiu[i] === '') {
        ;
      } else if ($(`input[name='${i}'][value='${backVar.yaoqiu[i]}']`).val()) {
        $(`input[name='${i}'][value='${backVar.yaoqiu[i]}']`).click()
      } else {
        $(`input[name='${i}_zidingyi']`).click()
        $(`input[name='${i}_zidingyi']`).val(backVar.yaoqiu[i])
        $(`input[name='${i}_zidingyi']`).change()
      }
    } else $(`input[name='${i}'][value='${backVar.yaoqiu[i]}']`).click()
  }
}

/** 回填diy表单 */
function writeBackDIYForm (data) {
  let id = data.m_group
  let value = data.m_value
  let formID = data.group
  let dataBackURL = String($('#get_free_form_data').val())
  try {
    let backVar = JSON.parse(window.backVar.tag_check_ori).cpclass
  } catch (err) {
    console.log('回填数据丢失')
  }

  function genDIYNumberLine (Obj, uniID, DIYFormDataId) {
    let resData = {
      mainData: '',
      altData: ''
    }
    $.ajax(dataBackURL, {
      method: 'POST',
      data: {md_id: DIYFormDataId},
      async: false
    }).done(function (data) {
      if (data.code !== '1') {
        console.log(`不能正确请求数据，位于：genDIYNumberLine(),message为：${data.message}`)
      } else {
        let res = data.data
        resData.mainData = res.maindata
        resData.altData = res.altdata
      }
    }).fail(function () {
      throw new Error('通信失败，请检查网络，来自：不能正确请求数据，位于：genDIYNumberLine()')
    })
    return `
    <div class="input_wrap number_input" id='hidden_from_backend${uniID}'>
      <div class="title"><input type="text" form='not_submit' name="[title]" placeholder="名称" value='${Obj.title}' readonly></div>
      <!-- 固定隐藏input，用于后端分辨该行表单类型 -->
      <input type='hidden' name='type' value='1'>
      <div class="alt_data">
        <select
          form = 'not_submit' name="[alt_data]"
          aria-multiple = 'false'
          aria-placeholder="请选择取值方向"
        >
          <option></option>
          <optgroup label="">
              <option value="大于" ${resData.altData === '大于' ? 'selected' : ''}>大于</option>
              <option value="大于等于" ${resData.altData === '大于等于' ? 'selected' : ''}>大于等于</option>
              <option value="小于" ${resData.altData === '小于' ? 'selected' : ''}>小于</option>
              <option value="小于等于" ${resData.altData === '小于等于' ? 'selected' : ''}>小于等于</option>
              <option value="等于" ${resData.altData === '等于' ? 'selected' : ''}>等于</option>
            </optgroup>
        </select>
      </div>
      <div class="main_data">
        <input type="text" form='not_submit' name="[main_data]" placeholder="数值" value='${resData.mainData}'>
      </div>
    </div>
    <script id='tempmlScript${uniID}'>
      $('#hidden_from_backend${uniID} .alt_data select').select2({
        placeholder: '请选择取值方向',
        tags: false,
        multiple: false,
        width: 'element'
      }).val('${resData.altData}').trigger('change')
      setTimeout(()=>{$('#tempmlScript${uniID}').remove()}, 0)
    </script>
    `.trim()
  }
  function genDIYSLine (Obj, uniID, DIYFormDataId) {
    let resData = {
      mainData: '',
      altData: ''
    }
    $.ajax(dataBackURL, {
      method: 'POST',
      data: {md_id: DIYFormDataId},
      async: false
    }).done(function (data) {
      if (data.code !== '1') {
        console.log(`不能正确请求数据，位于：genDIYSLine(),message为：${data.message}`)
      } else {
        let res = data.data
        resData.mainData = res.maindata
        resData.altData = res.altdata
      }
    }).fail(function () {
      throw new Error('通信失败，请检查网络，来自：不能正确请求数据，位于：genDIYSLine()')
    })

    let options = ``
    let templ = `
    <div class="input_wrap single_select" id='hidden_from_backend${uniID}'>
      <div class="title"><input type="text" form='not_submit' name="[title]" placeholder="名称" value='${Obj.title}' readonly></div>
      <!-- 固定隐藏input，用于后端分辨该行表单类型 -->
      <input type='hidden' name='type' value='2'>
      <div class="alt_data">
        <select
          form = 'not_submit' name="[alt_data]"
        >
          <optgroup label="暂无选项"></optgroup>
        </select>
      </div>
      <div class="main_data">
          <select
            form = 'not_submit' name="[main_data]"
          >
            <option inori-id='here-inori'></option>
          </select>
      </div>
    </div>
    <script id='tempmlScript${uniID}'>
      $('#hidden_from_backend${uniID} .alt_data select').select2({
        placeholder: '无需选择',
        tags: false,
        multiple: false,
        width: 'element'
      })
      $('#hidden_from_backend${uniID} .main_data select').select2({
        placeholder: '请选择具体选项',
        tags: false,
        multiple: false,
        width: 'element'
      }).val(null).trigger('change')
      setTimeout(()=>{$('#tempmlScript${uniID}').remove()}, 0)
    </script>
    `.trim()
    let flag = false
    $.each(Obj.main_data, function (index, opn) {
      /* 其实 `text === value` */
      if (resData.mainData === opn.key) {
        options += `<option value='${opn.value}' inori-data='${opn.key}' selected>${opn.text}</option>`
        flag = true
      } else {
        options += `<option value='${opn.value}' inori-data='${opn.key}'>${opn.text}</option>`
      }
    })
    if (flag) templ = templ.replace(/\.val\(null\)\.trigger\('change'\)/, '')
    return templ.replace(`<option inori-id='here-inori'></option>`, options)
  }
  function genDIYMLine (Obj, uniID, DIYFormDataId) {
    let resData = {
      mainData: {
        id: [],
        value: []
      },
      altData: ''
    }
    $.ajax(dataBackURL, {
      method: 'POST',
      data: {md_id: DIYFormDataId},
      async: false
    }).done(function (data) {
      if (data.code !== '1') {
        console.log(`不能正确请求数据，位于：genDIYMLine(),message为：${data.message}`)
      } else {
        let res = data.data
        resData.mainData = {
          id: String(res.maindata).split(','),
          value: []
        }
        resData.altData = res.altdata
      }
    }).fail(function () {
      throw new Error('通信失败，请检查网络，来自：不能正确请求数据，位于：genDIYMLine()')
    })

    let options = '<optgroup label="">'
    let templ = `
    <div class="input_wrap multiple_select" id='hidden_from_backend${uniID}'>
      <div class="title"><input type="text" form='not_submit' name="[title]" placeholder="名称" value='${Obj.title}' readonly></div>
      <!-- 固定隐藏input，用于后端分辨该行表单类型 -->
      <input type='hidden' name='type' value='3'>
      <div class="alt_data">
        <select
          form = 'not_submit' name="[alt_data]"
        >
          <optgroup label="">
              <option value="同时符合" ${resData.altData === '同时符合' ? 'selected' : ''}>同时符合</option>
              <option value="任意符合" ${resData.altData === '任意符合' ? 'selected' : ''}>任意符合</option>
            </optgroup>
        </select>
      </div>
      <div class="main_data">
          <select
            form = 'not_submit' name="[main_data][]"
          >
          <option inori-id='here-inori'></option>
          </select>
      </div>
    </div>
    <script id='tempmlScript${uniID}'>
      $('#hidden_from_backend${uniID} .alt_data select').select2({
        placeholder: '请选择具体选项（必填）',
        tags: false,
        multiple: false,
        width: 'element'
      })
      $('#hidden_from_backend${uniID} .main_data select').select2({
        placeholder: '请选择具体选项（必填）',
        // tags: true,
        multiple: true,
        tokenSeparators: [',', ' '],
        width: 'element',
        closeOnSelect: false
      }).inori_replace_placeholder
      setTimeout(()=>{$('#tempmlScript${uniID}').remove()}, 0)
    </script>
    `
    $.each(Obj.main_data, function (index, opn) {
      /* 其实 `text === value` */
      options += `<option value='${opn.value}' inori-data='${opn.key}'>${opn.text}</option>`
      // 组成val值
      if (resData.mainData.id.indexOf(opn.key) > -1) resData.mainData.value.push(`"${opn.text}"`)
    })
    options += '</optgroup>'
    return templ.replace(`<option inori-id='here-inori'></option>`, options).replace(/inori_replace_placeholder/, `val([${resData.mainData.value}]).trigger('change')`)
  }
  function genDIYForm (tagMessage, formID, formData) {
    let DIYFormDataId = ''
    let templWrap = `
    <div class="hdden_free_wrap_${tagMessage.id} hdden_free_wrap">
      <input type="hidden" name="hidden_free[1][group_id]" value="${formID}">
      <div style="width:100%;height:1px;clear:both;"></div>
      <div class = "wrap_title">小类：${tagMessage.value}</div>
      <input type="hidden" class='hiddenLineCounter' name="lineCounter" value="3" form='not_submit'>
      <input type="hidden" name="hidden_free[1][id]" value="${tagMessage.id}">
      <input type="hidden" name="hidden_free[1][value]" value="${tagMessage.value}">

      <!-- 表单插入 -->

      <!-- 最后一个元素必须是div，插入元素定位为最后一个div之前 -->
      <div class="button">
        页面提交前必须先提交本区域！
        <br>
        <button onclick='postThisHiddenLine(this, event, "second")'>保存</button>
      </div>
    </div>
    `.trim()
    let templWrapReplace = ``
    const switchObj = {
      1: genDIYNumberLine,
      2: genDIYSLine,
      3: genDIYMLine
    }
    $.each(formData, function (index, Obj) {
      try {
        const tempObj = JSON.parse(backVar.tag_check_ori).cpclass
        for (let e of tempObj.keys()) {
          for (let myDataItem of tempObj[e].my_data) {
            if (myDataItem.m_group === `${tagMessage.id}_${index}`) {
              DIYFormDataId = myDataItem.md_id
            }
          }
        }
      } catch (err) {
        console.log(err)
        console.log('回填数据失败，没有数据变量')
      }
      templWrapReplace += switchObj[Obj.input_type](Obj, `${formID}_${tagMessage.id}_${index}`, DIYFormDataId)
    })
    templWrap = templWrap.replace(`<!-- 表单插入 -->`, templWrapReplace)
    $('#hdden_free_form_wrap').append(templWrap)
    console.log('done')
    layer.closeAll('loading')
  }

  genDIYForm({id: id, value: value}, formID, data.formData)
}
